package controller

import (
	"back-end/internal/model"
	"back-end/internal/service"
	"back-end/pkg/common"
	"github.com/gin-gonic/gin"
)

type AuthController struct {
	userService service.UserService
	authService service.AuthService
}

func (a *AuthController) Name() string {
	return "auth"
}
func (a *AuthController) RegisterRoute(api *gin.RouterGroup) {
	api.POST("/login", a.Login)
	api.POST("/register", a.Register)
}
func NewAuthController(us service.UserService, as service.AuthService) Controller {
	return &AuthController{
		userService: us,
		authService: as,
	}
}

func (a *AuthController) Login(ctx *gin.Context) {
	loginInfo := new(model.LoginUser)
	if err := ctx.ShouldBindJSON(loginInfo); err != nil {
		common.FailedResponse(ctx, 401, err)
		return
	}
	result, err := a.authService.Login(loginInfo)
	if err != nil {
		common.FailedResponse(ctx, 401, err)
		return
	}
	common.SuccessResponse(ctx, result)
}

func (a *AuthController) Register(ctx *gin.Context) {
	registerInfo := new(model.RegisterUser)
	if err := ctx.ShouldBindJSON(registerInfo); err != nil {
		common.FailedResponse(ctx, 400, err)
		return
	}
	user := registerInfo.GetUser()
	result, err := a.userService.Create(user)
	if err != nil {
		common.FailedResponse(ctx, 400, err)
		return
	}
	common.SuccessResponse(ctx, result)
}
